package com.yundasys.lab06ratelimitannotation.service.impl;

import com.yundasys.lab06ratelimitannotation.service.LuaScriptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jiangta
 * @version 1.0
 * @date 2021/6/10 11:37 上午
 */
@Service("luaScriptService")
public class LuaScriptServiceImpl implements LuaScriptService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate2;

    private DefaultRedisScript<List> getRedisScript;

    @PostConstruct
    public void init() {
        getRedisScript = new DefaultRedisScript<>();
        getRedisScript.setResultType(List.class);
        getRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("luascript/LimitLoadTimes.lua")));
    }

    @Override
    public void redisAddScriptExec() {

        /**
         * List设置lua的KEYS
         */
        List<String> keyList = new ArrayList();
        keyList.add("count");
        keyList.add("rate.limiting:127.0.0.1");

        /**
         * 用Mpa设置Lua的ARGV[1]
         */
        Map<String,Object> argvMap = new HashMap<String,Object>();
        argvMap.put("expire",10000);
        argvMap.put("times",10);
        //String args = "{\"expire\",10000,\"times\",10}";

        /**
         * 调用脚本并执行
         */
        List result = redisTemplate2.execute(getRedisScript,keyList, argvMap);
        System.out.println(result);
    }
}
